using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.IO;

namespace WeatherRouter.Model
{
    [XmlRoot(ElementName = "Weather")]
    public class DaySpanList : List<DaySpan>
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public DaySpanList()
        { }

        public void LoadXml(string fileName)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            if (fileName.Length == 0)
                throw new ArgumentException("File name should be specified.");

            LoadXmlHelper(new XmlTextReader(fileName));            
        }

        /// <summary>
        /// Loads list of DaySpan objects from string.
        /// </summary>
        /// <param name="content">DaySpan list.</param>
        public void LoadXmlFromFeedContent(string content)
        {
            if (content == null)
                throw new ArgumentNullException("content");
            
            if (content.Length == 0)
                throw new ArgumentException("Content could not be empty.");

            TextReader reader = new StringReader(content);
            LoadXmlHelper(new XmlTextReader(reader));
        }

        /// <summary>
        /// Helper method that actually loads xml from reader.
        /// </summary>
        /// <param name="reader">Reader to load xml from.</param>
        private void LoadXmlHelper(XmlTextReader reader)
        {
            XmlSerializer serializer = null;
            DaySpanList list = null;
            
            try
            {
                Clear();

                serializer = new XmlSerializer(typeof(DaySpanList));

                if (serializer.CanDeserialize(reader))
                {
                    list = serializer.Deserialize(reader) as DaySpanList;

                    AddRange(list);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("Error while trying to load xml " + ex.ToString());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
    }
}
